<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>D3交互式数据可视化</title>
		<style>
			svg{
				border:1px solid red;
				display: block;
				margin: 10px auto;
			}
			.bar{
				text-align: center;
			}
		</style>
	</head>
	<body>
		<ul>
			<li>柱形图：矩形、坐标轴、文字</li>
		</ul>
		<!-- <rect x="20" y="20" width="20" height="20" rx="4" ry="4" style="fill:steelblue;stroke:blue;stroke-width:2;opacity:.5" /> -->
		<div class="bar">
			<button onclick="mySort()">排序</button>
			<button onclick="myAdd()">增加数据</button>
		</div>
		<script src="js/d3_3.5.7.js"></script>
		<script>
			var dataset = [20,30,60,40,50,80];
			const width = 300;
			const height = 300;
			var svg = d3.select(".bar").append("svg").attr("width",width).attr("height",height);
			var padding = {top:20,right: 20,bottom:20,left: 20};
			var rectStep = 35;
			var rectWidth = 30;
			draw()
			
			function draw() {
				var updateRect = svg.selectAll("rect").data(dataset);
					updateRect.call(drawBar);
				
				updateRect.enter().append("rect").call(drawBar);
				updateRect.exit().remove();
				
				var updateText = svg.selectAll("text").data(dataset);
					updateText.call(drawText);
				updateText.enter().append("text").call(drawText);
				updateText.exit().remove();
			}
			
			function drawBar() {
				this.attr("fill","steelblue")
					.attr("x",function(d,i) {
						return padding.left + i * rectStep;
					})
					.attr("y",function(d) {
						return height - padding.bottom -d
					})
					.attr("width",rectWidth)
					.attr("height",function(d) {
						return d;
					});
			}
			function drawText() {
				this.attr("fill","white")
					.attr("font-size","14px")
					.attr("text-anchor","middle")
					.attr("x",function(d,i) {
						return padding.left + i * rectStep;
					})
					.attr("y",function(d) {
						return height - padding.bottom - d;
					})
					.attr("dx",rectWidth / 2)
					.attr("dy","1em")
					.text(function(d) {
						return d;
					})
			}
			function mySort() {
				dataset.sort(d3.ascending);
				draw()
			}
			function myAdd() {
				dataset.push(Math.floor(Math.random() * 100));
				draw();
			}
		</script>
	</body>
</html>